package com.tedu.ivos.geofence.service.impl;

import com.tedu.ivos.base.exception.ServiceException;
import com.tedu.ivos.base.response.StatusCode;
import com.tedu.ivos.geofence.mapper.GeofenceMapper;
import com.tedu.ivos.geofence.pojo.dto.GeofenceParam;
import com.tedu.ivos.geofence.pojo.dto.GeofenceQuery;
import com.tedu.ivos.geofence.pojo.entity.Geofence;
import com.tedu.ivos.geofence.pojo.vo.GeofenceVO;
import com.tedu.ivos.geofence.service.GeofenceService;
import com.tedu.ivos.vehicle.mapper.VehicleMapper;
import com.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import com.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class GeofenceServiceImpl implements GeofenceService {

    @Autowired
    GeofenceMapper geofenceMapper;
    @Autowired
    VehicleMapper vehicleMapper;
    @Override
    public List<GeofenceVO> selectGeofence(GeofenceQuery geofenceQuery) {
        log.debug("获取围栏信息的业务:{}",geofenceQuery);
        List<GeofenceVO> list = geofenceMapper.selectGeofence(geofenceQuery);

        return list;
    }

    @Override
    public void saveGeofence(GeofenceParam geofenceParam) {
        log.debug("保存或者修改围栏信息的业务:{}",geofenceParam);

        Geofence geofence=new Geofence();
        BeanUtils.copyProperties(geofenceParam,geofence);
        // 判断是新增还是修改
        if (geofence.getId()==null){
            log.debug("新增");
            geofence.setStatus("1");// 每个围栏新增加时设置为启用
            geofence.setCreateTime(new Date());
            geofenceMapper.insertGeofence(geofence);

        }else {
            log.debug("修改");
            geofence.setUpdateTime(new Date());
            geofenceMapper.updateGeofence(geofence);
        }

    }

    @Override
    public void deleteGeofence(Long id) {
        log.debug("删除围栏信息业务:{}",id);
        // 业务 ：判断该围栏是否绑定了车辆 如果有数据就不能删除
        // 1. 封装车辆数据层查询 查询条件
        VehicleQuery vehicleQuery=new VehicleQuery();
        vehicleQuery.setGeofenceId(id);
        // 2. 查询车辆信息
        List<VehicleVO> list=vehicleMapper.selectVehicle(vehicleQuery);
        // 3. 判断是否为空
        if (list.size()>0 && list !=null){//list !=null 需要对空指针进行预处理
            log.debug("该围栏绑定了车辆，不能删除,绑定的车辆的个数:{}",list.size());
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }else {
            geofenceMapper.deleteGeofenceByid(id);
        }

    }
}
